Python 24일 완성Day 13pythonintermediate
Python 24일 코스 - Day 13: 클래스 기초
· 읽기 2분
Day 13: 클래스 기초
클래스 정의
class Dog:
species = "Canis familiaris" # 클래스 변수
def __init__(self, name, age):
self.name = name # 인스턴스 변수
self.age = age
def bark(self):
return f"{self.name}이(가) 멍멍!"
def info(self):
return f"{self.name}, {self.age}살"
my_dog = Dog("바둑이", 3)
print(my_dog.bark()) # 바둑이이(가) 멍멍!
print(my_dog.info()) # 바둑이, 3살
클래스 변수 vs 인스턴스 변수
| 구분 | 클래스 변수 | 인스턴스 변수 |
|---|
| 위치 | 클래스 본문 | __init__ 내부 |
| 공유 | 모든 인스턴스 공유 | 각 인스턴스 고유 |
| 접근 | Class.var 또는 self.var | self.var |
은행 계좌 예제
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # 관례적 비공개
def deposit(self, amount):
if amount <= 0:
raise ValueError("입금액은 양수여야 합니다")
self._balance += amount
return self._balance
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("잔액이 부족합니다")
self._balance -= amount
return self._balance
def get_balance(self):
return self._balance
account = BankAccount("철수", 10000)
account.deposit(5000)
account.withdraw(3000)
print(f"잔액: {account.get_balance()}원") # 잔액: 12000원
프로퍼티
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("반지름은 음수일 수 없습니다")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
c = Circle(5)
print(c.area) # 78.53975
c.radius = 10
print(c.area) # 314.159
오늘의 연습문제
Student 클래스를 만들어 이름, 과목별 점수, 평균 계산 기능을 구현하세요.
Rectangle 클래스에 넓이, 둘레, 정사각형 여부를 프로퍼티로 구현하세요.
TodoList 클래스로 할 일 추가, 삭제, 완료 표시 기능을 만드세요.